package excelpptword2pdf.hsj.components.impl;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


import com.aspose.words.*;

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;

import excelpptword2pdf.hsj.components.AbstractPDFConverter;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

/**
 * txt,doc,docx,wps转pdf
 */
public class Word2ImageConverter extends AbstractPDFConverter {

	
	private static Logger logger = Logger.getLogger(Word2ImageConverter.class);
	
	
	public Word2ImageConverter() {
		super();
	}
	
	public Word2ImageConverter(String fontDir) {
		super(fontDir);
	}

	@Override
	protected void initFileType() {
		fileTypes.add("txt");
		fileTypes.add("doc");
		fileTypes.add("docx");
		fileTypes.add("wps");

	}

	@Override
	protected boolean matchLicense() {
		boolean result = false;
//		InputStream is = PDF2WordConverter.class.getClassLoader().getResourceAsStream("com/sbr/converter/components/licenses/license.xml");
		try {
		InputStream is = new ClassPathResource("license.xml").getInputStream();
		License wordLicense = new License();
			wordLicense.setLicense(is);
			result = true;
		} catch (Exception e) {
			logger.warn("载入word授权文件失败");
		}
		return result;
	}

	/**
	 * 多页转化
	 * @param sourceFile
	 * @param targetFile 文件根路径
	 * @param word2Png
	 */
	public void morePage(File sourceFile,String targetFile,int word2Png ){
		Document doc = null;
		FileOutputStream os = null;
		try {
			//os = new FileOutputStream(targetFile);
			doc = new Document(sourceFile.getAbsolutePath());
			ImageSaveOptions options = new ImageSaveOptions(word2Png);
			options.setPrettyFormat(true);
			options.setUseAntiAliasing(true);
			options.setUseHighQualityRendering(true);
			List<BufferedImage> imageList = new ArrayList<BufferedImage>();
			for (int i = 0; i < doc.getPageCount(); i++) {
				options.setPageIndex(i);
				OutputStream output = new ByteArrayOutputStream();
				doc.save(output, options);
				ImageInputStream imageInputStream = javax.imageio.ImageIO.createImageInputStream(parse(output));
				imageList.add(javax.imageio.ImageIO.read(imageInputStream));
			}
			BufferedImage mergeImage = mergeImage(false, imageList);
			//将其保存在C:/imageSort/targetPIC/下
			ImageIO.write(mergeImage, "png", new File("e://2.png"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 合并任数量的图片成一张图片
	 *
	 * @param isHorizontal true代表水平合并，fasle代表垂直合并
	 * @param imgs         待合并的图片数组
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
		// 生成新图片
		BufferedImage destImage = null;
		// 计算新图片的长和高
		int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
		// 获取总长、总宽、最长、最宽
		for (int i = 0; i < imgs.size(); i++) {
			BufferedImage img = imgs.get(i);
			allw += img.getWidth();

			if (imgs.size() != i + 1) {
				allh += img.getHeight() + 5;
			} else {
				allh += img.getHeight();
			}


			if (img.getWidth() > allwMax) {
				allwMax = img.getWidth();
			}
			if (img.getHeight() > allhMax) {
				allhMax = img.getHeight();
			}
		}
		// 创建新图片
		if (isHorizontal) {
			destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
		} else {
			destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
		}
		Graphics2D g2 = (Graphics2D) destImage.getGraphics();
		g2.setBackground(Color.LIGHT_GRAY);
		g2.clearRect(0, 0, allw, allh);
		g2.setPaint(Color.RED);

		// 合并所有子图片到新图片
		int wx = 0, wy = 0;
		for (int i = 0; i < imgs.size(); i++) {
			BufferedImage img = imgs.get(i);
			int w1 = img.getWidth();
			int h1 = img.getHeight();
			// 从图片中读取RGB
			int[] ImageArrayOne = new int[w1 * h1];
			// 逐行扫描图像中各个像素的RGB到数组中
			ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
			if (isHorizontal) {
				// 水平方向合并
				// 设置上半部分或左半部分的RGB
				destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1);
			} else {
				// 垂直方向合并
				// 设置上半部分或左半部分的RGB
				destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1);
			}
			wx += w1;
			wy += h1 + 5;
		}


		return destImage;
	}
	public static ByteArrayInputStream parse(OutputStream out) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos = (ByteArrayOutputStream) out;
		ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		return swapStream;

	}
	/**
	 * 单页转换
	 * @param sourceFile
	 * @param targetFile 输出路径
	 */
	@Override
	protected void convert2PDF(File sourceFile,File targetFile) {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(targetFile);
			Document doc = new Document(sourceFile.getAbsolutePath());

			doc.save(os, SaveFormat.PNG);
		} catch (FileNotFoundException e) {
			logger.error("输出到"+targetFile+"错误:"+e);
		} catch (Exception e) {
			logger.error("转换word出错:"+e);
		}finally {
			if(os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error("关闭输出流出错:"+e);
				}
			}
		}
	}
	
	

}
